import {
	defineStore
} from 'pinia'
import {
	ref,
	watch
} from 'vue'
import {
	getSwiper,
	getGoodList,
	getGoodListFilter
} from '../api/home.api.js'

export const useHomeStore = defineStore(
	'home',
	() => {
		const swiperData = ref([]) // 轮播图
		const goodListData = ref([]) // 商品列表数据
		const searchRecord = ref([]) // 搜索记录
		const sortData = ref(0)  // 排序条件
		const goodListFilter = ref([])

		// 获取轮播图数据
		const getSwiperData = async () => {
			let result = await getSwiper()
			swiperData.value = result.message
		}
		// 获取商品列表数据
		const getGoodListData = async () => {
			let result = await getGoodList()
			goodListData.value = result.message
		}
		// 去首页
		const goHome = () => {
			uni.switchTab({
				url: '/pages/index/index'
			})
			goodListFilter.value = []
		}
		// 跳转搜索
		const goSearch = () => {
			uni.navigateTo({
				url: '/pages/search/search'
			})
		}
		// 监听搜索记录，限制记录数量
		watch(searchRecord, (newValue, oldValue) => {
			if (newValue.length > 10) {
				searchRecord.value = newValue.slice(-10)
			}
		}, {
			deep: true
		})
		// 通过筛选获取商品列表
		const getGoodListFilterData = async (value) => {
			let sort;
			if(sortData.value === 0){
				sort = 'buy'
			}else if(sortData.value === 1){
				sort = 'likes'
			}else if(sortData.value === 2){
				sort = 'sell_price'
			}
			let result = await getGoodListFilter(value,sort)
			goodListFilter.value = result
		}
		


		return {
			// 数据
			swiperData,
			goodListData,
			searchRecord,
			sortData,
			goodListFilter,
			// 方法
			getSwiperData,
			getGoodListData,
			goHome,
			goSearch,
			getGoodListFilterData

		}
	}, {
		persist: {
			storage: {
				getItem(key) {
					return JSON.parse(uni.getStorageSync(key)); // 手动替代 destr
				},
				setItem(key, value) {
					uni.setStorageSync(key, JSON.stringify(value));
				},
			},
		}
	}
)